<template>
  <div class="global-container">
    <div class="gray-line"></div>
    <Atable :tableData="tableData" :tableModel="tableModel">
      <template #down="{ row }">
        <i class="el-icon-s-order"></i>
        {{ row.name }}
      </template>
      <template #actions="{ row }">
        <template v-if="tabsActive == '5'">
          <el-button @click="mwrDownload(row)" type="primary" size="small"
          >下载</el-button>
        </template>
        <template v-else-if="tabsActive == '4'">
          <el-button @click="download(row)" type="primary" size="small"
          >下载</el-button>
        </template>
        <template v-else>
          <el-button @click="view(row)" type="primary" size="small"
          >查看</el-button
          >
          <el-button @click="assess(row)" type="primary" size="small"
          >评价</el-button
          >
        </template>
      </template>
    </Atable>
  </div>
</template>
<script>
import Atable from '@/components/Table/Atable';
import businessApi from '@/api/business';
import apply from '@/assets/js/apply';
import dayjs from "dayjs";

export default {
  props: {
    bussType: {
      type: String,
    },
  },
  components: { Atable },
  data() {
    return {
      searchData: {
        pageNum: 1,
        pageSize: 10,
        name: null, //风险指标名称
        type: 0,
      },
      tableData: [],
      tableModel: [],
      statusMap: {
        0: '未提交',
        1: '待受理',
        2: '不予受理',
        3: '待审查',
        4: '不予许可',
        5: '准予许可',
      },
      statusTabsMap: {
        1: '5',
        2: '4',
        3: '2',
        4: '5'
      },
      certTypeMap: {
        '1': '二级造价工程师（水利工程）',
        '2': '水利工程质量检测单位资质认定（乙级）',
        '3': '三类人员安全生产考核合格证书'
      }
    };
  },

  destroyed() {
    this.$store.commit('tabs/setTabsActive', '');
    this.$store.commit('tabs/setTabsOptions', []);
  },
  mounted() {
    const activeIndex = this.$route.params.tabsActive || '1';
    this.$store.commit('tabs/setTabsActive', activeIndex);
    let tabs = [
      { label: '准予许可', value: '1' },
      { label: '不予许可', value: '2' },
      { label: '不予受理', value: '3' },
      { label: '证书查询', value: '4' },
      { label: '查询水利部系统证书', value: '5' }]
    this.$store.commit('tabs/setTabsOptions', tabs);
    this.getTable();
  },
  computed: {
    tabsActive() {
      return this.$store.state.tabs.tabsActive;
    },
    certType() {
      return businessApi.getCertType(this.bussType);
    }
  },
  watch: {
    tabsActive: {
      handler() {
        this.getTable();
      },
      deep: true,
    },
  },
  methods: {
    async getTable() {
      this.$emit('loading', true);
      this.tableModel = this.tabsActive == '4' || this.tabsActive == '5' ? [
        {
          prop: 'certCode',
          label: '证书编号',
        },
        {
          prop: 'certType',
          label: '证书类型',
          render: (row) => {
            return this.certTypeMap[row.certType];
          },
        },
        {
          prop: 'appPer',
          label: '申请人',
        },
        {
          prop: 'employUnit',
          label: '聘用单位',
        },
        {
          prop: 'validTime',
          label: '有效期',
          render: (row) => {
            if (row.effStartTime && row.effEndTime) {
              return `${row.effStartTime}至${row.effEndTime}`;
            }
            return '';
          },
        },
        {
          prop: 'certTime',
          label: '发证日期',
        },
        {
          prop: 'actions',
          label: '操作',
          width: '100',
          slot: 'actions',
        },
      ] : [
        {
          type: 'index',
          label: '序号',
        },
        {
          prop: 'code',
          label: '事项编号',
        },
        {
          prop: 'name',
          label: '事项名称',
          width: '300px',
        },
        {
          prop: 'sqTime',
          label: '申请时间',
          render: (row) =>
              row.sqTime ? this.$dayjs(row.sqTime).format('YYYY-MM-DD') : '',
        },
        {
          prop: 'slTime',
          label: '审查时间',
          render: (row) =>
              row.scTime ? this.$dayjs(row.scTime).format('YYYY-MM-DD') :
                  (row.slTime ? this.$dayjs(row.slTime).format('YYYY-MM-DD') : ''),
        },
        {
          prop: 'actions',
          label: '操作',
          slot: 'actions',
        },
      ];
      this.tableData = [];
      let params = {
        pageNo: 1,
        pageSize: 10,
        // 根据tabsActive获取不同的status
        status: this.statusTabsMap[this.tabsActive],
      }
      if (this.tabsActive == '5') {
        params = {
          holderCode: this.$store.state.user.userInfo.paperCode,
        }
      } else if (this.tabsActive == '4') {
        params = {
          ...params,
          userCert: '1',
        }
      } else {
        params = {
          ...params,
          bussType: this.bussType,
        }
      }
      await this.getList(params);
    },
    async getList(params) {
      if (this.tabsActive == '5') {
        await businessApi.getCertsFromMwr(params)
            .then((res) => {
              if (res && res.status==200) {
                const {data} = res;
                const certList = data?.data;
                if (certList && certList.length) {
                  this.tableData = certList.map((item) => {
                    const {REG_INFO, ISSU_DATE,
                      VAL_PER_FROM, VAL_PER_TO,
                      HOLDER_INFO,
                    } = item;
                    return {
                      ...item,
                      certCode: item.CERT_NUM_CODE,
                      certType: '3',
                      appPer: HOLDER_INFO.HOLDER_NM,
                      employUnit: REG_INFO.ENT_NAME,
                      effStartTime: dayjs(VAL_PER_FROM).format('YYYY-MM-DD'),
                      effEndTime: dayjs(VAL_PER_TO).format('YYYY-MM-DD'),
                      certTime: dayjs(ISSU_DATE).format('YYYY-MM-DD'),
                    };
                  });
                }
              }
            }).finally(() => {
              this.$emit('loading', false);
            });
      }
      else {
        // 获取列表
        businessApi.getStepsList(params)
            .then((res) => {
              if (res.records) {
                const records = res.records.map((item) => {
                  return {
                    ...item,
                    code: apply.applyCode[item.bussType],
                    name: apply.applyName[item.bussType],
                  };
                });
                this.tableData = records;
              }
            }).finally(() => {
          this.$emit('loading', false);
        });
      }
    },
    view(row) {
      let type =
        +row.status > 1
          ? +row.status > 3
            ? 'process'
            : 'accept'
          : 'unhandled';
      this.$router.push({
        path: '/dockPersonalProcessMain',
        query: {
          type: type,
          id: row.id,
          bussType: row.bussType,
          userId: row.userId,
          disabled: true,
          routePathName: this.$route.name,
          routeCurrentParams: {
            tabsActive: this.$store.state.tabs.tabsActive,
            bussType: row.bussType,
          },
        },
      });
    },
    async assess(row) {
      let params = {
        id: row.id,
      };
      const res = await businessApi.getJudgeWeb(params);
      window.open(res);
    },
    download(row) {
      businessApi.getCertificateById({
        id: row.id
      }).then(res => {
        // const { fileUri } = res.certFile;
        if (res.certFile && res.certFile.fileUri) {
          // download ofd
          window.location.href = res.certFile.fileUri;
          // this.previewUrl = fileUri;
          // this.previewVisible = true;
        } else {
          this.$message.error('暂无证书');
        }
      });
    },
    mwrDownload(row) {
      businessApi.downloadCertFromMwr({
        id: row.ID,
        certType: '3'
      }).then(res => {
        if (res && res.data) {
          const fileType = res.data.fileType;
          const fileBase64 = res.data.fileData;
          const fileName = row.CERT_NUM_CODE;
          const file = this.base64ToFile(fileBase64, fileName, fileType);
          // download ofd
          const url = window.URL.createObjectURL(file);
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', `${fileName}.${fileType}`);
          document.body.appendChild(link);
          link.click();
        }
      })
    },
    base64ToFile(fileData, fileName, fileType) {
      const bstr = atob(fileData);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], fileName, {type: fileType});
    },
  },
};
</script>
<style lang="scss" scoped>
.gray-line {
}
</style>
